package utils;

import java.security.MessageDigest;

public class EncryptUtil {

    // 随机字符串当公钥
    private static final String PUL_SALT = "d7Jz81B0ocB5hJBZ5WxGeGOty61FGh2T";

    public static String encrypt(String str) {
        str = PUL_SALT.concat(str);
        String md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");  // 创建一个md5算法对象
            byte[] messageByte = str.getBytes("UTF-8");
            byte[] md5Byte = md.digest(messageByte);              // 获得MD5字节数组,16*8=128位
            md5 = bytesToHex(md5Byte);                            // 转换为16进制字符串
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5;
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexStr = new StringBuffer();
        int num;
        for (int i = 0; i < bytes.length; i++) {
            num = bytes[i];
            if (num < 0) {
                num += 256;
            }
            if (num < 16) {
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }

    public static void main(String[] args) {
        System.out.printf(encrypt("12121212"));
        // 8CE87B8EC346FF4C80635F667D1592AE
    }
}
